package com.novel.authorization.tenant;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import com.novel.base.config.properties.IgnoreProperties;
import com.novel.base.constants.CommonConstants;
import com.novel.base.exception.CustomException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 樊温军
 * @date 2025/3/19 下午12:14
 */
@Slf4j
@Component
@Order(-1)
public class TenantContextHolderFilter extends GenericFilterBean {
    @Resource
    private IgnoreProperties ignoreProperties;

    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        for (String ignoreUrl : ignoreProperties.getIgnoreUrls()) {
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            if (antPathMatcher.match(ignoreUrl, request.getRequestURI())) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        String tenantId = request.getHeader(CommonConstants.TENANT_ID_HEADER);
        log.info("获取header中的租户ID为:{}", tenantId);
        log.info("请求地址：{}", request.getRequestURI());
        if (StrUtil.isEmpty(tenantId)) {
            throw new CustomException("租户ID不能为空");
        }
        TenantContextHolder.setTenantId(tenantId);
        filterChain.doFilter(request, response);
        TenantContextHolder.clear();
    }
}

